// 跳转到注册文档的链接
let goRegister = document.querySelector(".goRegister");
// 跳转到登录页面的链接
let goLogin = document.querySelector(".goLogin");
// 注册页面
let register = document.querySelector(".register");
// 登录页面
let login = document.querySelector(".login");
// 注册按钮
let btnregister = document.querySelector(".btnregister");
// 登陆按钮
let btnlogin = document.querySelector(".btnlogin");
// 获取注册面板中的用户名和密码
let rusername = document.querySelector('.register  [name="username"]');
let rpassword = document.querySelector('.register  [name="password"]');
// 获取登陆面板中的用户名和密码
let lusername = document.querySelector('.login  [name="username"]');
let lpassword = document.querySelector('.login  [name="password"]');

// 点击注册链接
goRegister.addEventListener("click", function () {
  login.style.display = "none";
  register.style.display = "block";
});
// 点击登录链接
goLogin.addEventListener("click", function () {
  login.style.display = "block";
  register.style.display = "none";
});

// ==================================================================
// 表单验证
function test() {
  return {
    fields: {
      username: {
        validators: {
          notEmpty: {
            message: "用户名不能为空",
          },
          stringLength: {
            min: 2,
            max: 15,
            message: "用户名长度不能小于2位或超过15位",
          },
        },
      },
      password: {
        validators: {
          notEmpty: {
            message: "密码不能为空",
          },
          stringLength: {
            min: 6,
            max: 15,
            message: "密码长度不能小于6位或超过15位",
          },
        },
      },
    },
  };
}

//  注册
$(".register form")
  .bootstrapValidator(test())
  .on("success.form.bv", function (e) {
    // btnregister.addEventListener("click", function (e) {
    e.preventDefault();
    // 账号和密码
    let data = {
      username: rusername.value,
      password: rpassword.value,
    };
    console.log(data)
    axios({
      url: "/api/register",
      method: "post",
      data,
    }).then((res) => {
      console.log(res);
      if (res.data.code == 0) {
        toastr.success("注册成功");
        // 切换到登录页面
        login.style.display = "block";
        register.style.display = "none";
      } else if (res.data.code == 1) {
        toastr.warning("注册失败");
      }
    });
  });

// 登录
$(".login form")
  .bootstrapValidator(test())
  .on("success.form.bv", function (e) {
    // login.addEventListener("click", function (e) {
    e.preventDefault();
    let data = {
      username: lusername.value,
      password: lpassword.value,
    };
    axios({
      url: "/api/login",
      method: "post",
      data,
    }).then((res) => {
      console.log(res);
      if (res.data.code == 0) {
        toastr.success("登录成功");
        localStorage.setItem("888token", res.data.token);
        location.href = "./index.html";
      } else if (res.data.code == 1) {
        toastr.warning("登录失败");
      }
    });
  });
